package io.renren.modules.service_controller.service.impl;

import io.renren.modules.Service.entity.ServiceEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.service_controller.dao.ServiceControllerDao;
import io.renren.modules.service_controller.entity.ServiceControllerEntity;
import io.renren.modules.service_controller.service.ServiceControllerService;


@Service("serviceControllerService")
public class ServiceControllerServiceImpl extends ServiceImpl<ServiceControllerDao, ServiceControllerEntity> implements ServiceControllerService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ServiceControllerEntity> page = this.page(
                new Query<ServiceControllerEntity>().getPage(params),
                new QueryWrapper<ServiceControllerEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ServiceControllerEntity> listWithTree() {
        //查出所有分类
        //组装成父子的树形结构
        List<ServiceControllerEntity> entities = baseMapper.selectList(null);

        //查询一级服务
        List<ServiceControllerEntity> level1 = entities.stream().filter((serviceControllerEntity)->{
            return serviceControllerEntity.getParentId() == 0;
        }).map((memu)->{
            memu.setChildren(getChildern(memu,entities));
            return memu;
        }).sorted((menu1, menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1;
    }

    //递归查找所有菜单的子菜单
    private List<ServiceControllerEntity> getChildern(ServiceControllerEntity root
    , List<ServiceControllerEntity> all){
        List<ServiceControllerEntity> children = all.stream().filter(serviceControllerEntity -> {
            return serviceControllerEntity.getParentId() == root.getMenuId();
        }).map(serviceControllerEntity -> {
            //找到子菜单
            serviceControllerEntity.setChildren(getChildern(serviceControllerEntity,all));
            return serviceControllerEntity;
        }).sorted((menu1,menu2)->{
            //菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}